;
(function (call) {
    var zbsf = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        latestTime: null,
        isFirstGetTime: true,
        router: {
            cfg: "/business/kgyb/json/zbsf.json",
            gridData: '/sjyb/queryModelGridDataByZB',
            getLatestTime: 'zhfx/gridKGYB/querySkGridData/LatestTime',
            //queryMusicInfo: 'http://10.226.112.66:9097/musicInfo/queryMusicInfo',
            queryMusicInfo: 'http://10.226.120.52:9091/musicInfo/queryMusicInfo',
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
        },
        // 获取最新起报时间
        getLatestTime: function (elementId) {
            var that = this;
            that.isFirstGetTime = false;
            var param = {
                element: elementId
            };
            $.ajax({
                url: this.router.getLatestTime,
                type: 'GET',
                dataType: 'json',
                async: false,
                data: param
            }).done(function (res) {
                if (res.isSuccess && res.data) {
                    that.latestTime = res.data;
                    $(".product-zbsf-datepicker #zbsfDate").IDatePicker().setVal(that.latestTime);
                }
            })
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");
                    
                    $('.product-zbsf-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="zbsfDate" data-options="${item.dateOptions}" value="">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-zbsf-datepicker .date-panel", {
                        query: function query() {
                            zbsf.disabledEle();
                            zbsf.buildLastTime(function () {
                                zbsf.getMultiGridData();
                            });
                        }
                    });
                    that.buildProContent(data.basic_pro[item.id] || []);
                    that.disabledEle();
                })
                $(".product-zbsf-tab ul").append($li);
            })
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-zbsf-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');
                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);
                $item.append($title);

                if (item.content) {
                    var $ul = $('<ul>');
                    item.content.forEach(function (pro) {
                        var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                        if (pro.selected)
                            $li.addClass("default");
                        $li.data('pro', pro);
                        if (pro.title)
                            $li.attr('title', pro.title);
                        if (pro.width)
                            $li.css("width", pro.width);
                        $ul.append($li);
                    })
                    $item.append($ul);
                }
                $(".product-zbsf-list").append($item);
            })
        },
        //当分为08或20时，部分元素不能点击，置灰
		disabledEle: function () {
            var baseDate = $(".product-zbsf-datepicker #zbsfDate").IDatePicker().getVal() + ":00";
            var hour = new Date(baseDate).getHours();
            var flag = hour == 8 || hour == 20 ? true : false;
			$(".product-zbsf-list li").each(function () {
				var $obj = $(this);
				var pro = $obj.data("pro");
				if (pro.interval == 24) {
					if (!flag) {
                        if ($obj.hasClass("active")) {
                            $obj.click();
                        }
						$obj.addClass("preventEventLi");
						$obj.children().addClass("preventEvent");
					} else {
						$obj.removeClass("preventEventLi");
						$obj.children().removeClass("preventEvent");
					}
				}
			})
		},
        //点击显示pdf技术说明
        showTechPdf:function(id,path){
            var that = this;
            if (CafeJS.ModalBoxExist(id)) {
                CafeJS.ModalBoxShow(id);
                return;
            }
            CafeJS.ModalBox({
                id: id,
                container: 'cafe-busis-container',
                title: "技术说明",
                width: 1300,
                height: 700,
                m_top: 70,
                m_right: 90,
                hasMask:true,
                hide: true,
                html: "<div id='"+id+"' style='width:100%;height:calc(100% - 10px)'></div>",
                showCall: function(obj) {
                    PDFObject.embed(path,"#"+id);
                },
                closed: function () { }
            });
        },
        buildLastTime: function (call) {
            var baseDate = $(".product-zbsf-datepicker #zbsfDate").IDatePicker().getVal() + ":00";
            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            debugger
            var that = this;
            var startTime = pro.time;
            var layers = that.getModels(pro.ele);
            var interval = pro.ele.interval ? pro.ele.interval*60 : 60;;

            this.playList = CafeJS.Timeline2({
    			appendTo : "#a-m-timeline",
    			curDate : startTime,
    			type : 1,
    			pro: pro,
    			dateOpt: {
                	dateFmt : 'yyyy-MM-dd hh:mm',
                	timeInterval: interval,
                	customHm: []
                },
                timeInterval: interval,
    			layers: layers,
    			gisId : that.mapId,
    			call : function(pro) {
    				CafeJS.layerManage.updateLayer(pro);
                    that.getGridData(pro, pro.time);
    			},
    			getPlayData: function(pro, timeArr) {
                    that.getGridData(pro, timeArr);
    			}
    		});
        },
        // 初始化图例
        initLegentpicker: function (ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [];
            $.each(layers, function (i, m) {
                layerIds.push(m.id);
            });
            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                seq: 'decrease',
                productId: ele.color_id,
                isShowSlider: true
            });
        },
        // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function (pro) {
                var proInfo = that.getProInfo(pro);
                var queryTime = that.playList.getCurTime();
                CafeJS.layerManage.updateLayerTime(queryTime, 'zbsf', null, pro.ele_id);
                that.getGridData(proInfo);
            })
        },
        getGridData: function (proInfo, timeArr) {
            var that = this;
            if (!proInfo) return;
            var element = proInfo.ele.ele_id;
            debugger
            var queryTime = that.playList.getCurTime() + ":00:00";
            var qbTime = new Date(proInfo.time).format('yyyy-MM-dd hh:mm:00');
            var period = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
			
           
            loading.add();

            var param = {
                    queryTime: $(".product-zbsf-datepicker #zbsfDate").IDatePicker().getVal() + ':00:00',
                    element: element,
                    modeType:"SCMOC-BESZ",
                    period:period,
                    interval:3
            }
            CafeJS.ajax({
                url: that.router.gridData,
                params: param,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, proInfo.ele);
                }
            })
        },

        decode64: function(base64) {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

            // Use a lookup table to find the index.
            var lookup = new Uint8Array(256);
            for (var i = 0; i < chars.length; i++) {
                lookup[chars.charCodeAt(i)] = i;
            }
            
            var bufferLength = base64.length * 0.75,
            len = base64.length, i, p = 0,
            encoded1, encoded2, encoded3, encoded4;
        
            if (base64[base64.length - 1] === "=") {
              bufferLength--;
              if (base64[base64.length - 2] === "=") {
                bufferLength--;
              }
            }
        
            var arraybuffer = new ArrayBuffer(bufferLength),
            bytes = new Uint8Array(arraybuffer);
        
            for (i = 0; i < len; i+=4) {
              encoded1 = lookup[base64.charCodeAt(i)];
              encoded2 = lookup[base64.charCodeAt(i+1)];
              encoded3 = lookup[base64.charCodeAt(i+2)];
              encoded4 = lookup[base64.charCodeAt(i+3)];
        
              bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
              bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
              bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
            }
        
            return arraybuffer;
        },
        // 绘制格点色斑图
        drawGridRawMap: function (data, ele) {
            var typeArr = this.getModels(ele);
            var color_id = ele.color_id;
            var legentCfg = CafeJS.Legentconfig().cfg();
            var colorObj = legentCfg[color_id];

            // 显示色斑和数值
            GIS.GridShow.showByTypes_raw(this.mapId, typeArr, data, {}, colorObj);
            CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
        },
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "zbsf-layer-" + m + "-" + pro.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function (proInfo) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid && !proInfo.ele.frames) {
                that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
            }
        },
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            $(".product-zbsf-list li.active").each(function () {
                if ($(this).data('pro').ele_id == eleid) {
                    $(this).click();
                    return false;
                }
            })
        },
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-zbsf-list li.active,.product-zbsf-list td.active").each(function () {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function (ele) {
            var name = '周边省份_'+ele.ele_name;
            var time = $(".product-zbsf-datepicker #zbsfDate").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'zbsf',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function (ele_id) {
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('zbsf-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-zbsf-list").off('click').on('click', 'li', function () {
                var pro = $(this).data('pro');
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);

                    that.clearGridLayer(pro.ele_id);
                    that.removeLayer(pro);
                } else {
                    $(this).siblings('li.active').click(); // 清除之前选中的

                    $(this).addClass("active");
                    if (that.isFirstGetTime)
                        that.getLatestTime(pro.ele_id);

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);

                    that.getGridData(proInfo);
                }
            })
            $('.product-zbsf-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                $(".product-zbsf-datepicker #zbsfDate").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $(".product-zbsf-datepicker #zbsfDate").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $(".product-zbsf-datepicker #zbsfDate").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            });
            $(".product-zbsf-tab li").first().click();
        }
    }
    if (typeof call === 'function') {
        CafeJS.zbsf = zbsf;
        call(zbsf);
    }
    window.zbsf = zbsf;
})(function (zbsf) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        zbsf.init();
    });
});
